package com.easy_helth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.easy_helth.common.R;
import com.easy_helth.entity.Admin;
import com.easy_helth.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    //    登录
    @PostMapping("/login")
    public R<Admin> login(HttpServletRequest request, @RequestBody Admin admin) {
        String password = admin.getPassword();

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername, admin.getUsername());
        Admin emp = adminService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("登录失败");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(password)) {
            return R.error("登录失败");
        }

        //5、查状态，如果为已禁用状态，则返回已禁用结果
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        //6、登录成功，将其id存入Session并返回登录成功结果
        request.getSession().setAttribute("admin", emp.getId());
        return R.success(emp);
    }

    /**
     * 退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("admin");
        return R.success("退出成功");
    }

    /**
     * 通过HttpServlet获取admin
     * @param admin
     * @param request
     * @return
     */
    @GetMapping("/getAdmin")
    public R<Admin> getAdmin(Admin admin ,HttpServletRequest request){
//        获取id
        int id = (int) request.getSession().getAttribute("admin");
        admin = adminService.getById(id);
        return R.success(admin);

    }


}

